var goyello = goyello || {};

goyello.view = function()
{
    var oList = $('#result');

    function fHtmlSpecialCharsDecode(string)
    {
        return string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    }

    function fFillFulForm(item)
    {
        item = item || {};
        $('#ADDRESSID').val(parseInt(item.ADDRESSID || ''));
        $('#LABEL').val(fHtmlSpecialCharsDecode(item.LABEL || ''));
        $('#STREET').val(fHtmlSpecialCharsDecode(item.STREET || ''));
        $('#HOUSENUMBER').val(fHtmlSpecialCharsDecode(item.HOUSENUMBER || ''));
        $('#POSTALCODE').val(fHtmlSpecialCharsDecode(item.POSTALCODE || ''));
        $('#COUNTRY').val(fHtmlSpecialCharsDecode(item.COUNTRY || ''));
        $('#CITY').val(fHtmlSpecialCharsDecode(item.CITY || ''));
    }

    function  fClearForm()
    {
        fFillFulForm(null);
    }

    function fCreateLiLabel(i)
    {
        return '[' + i.ADDRESSID + ']: ' + i.LABEL + ', ' +
                i.STREET + ', ' + i.HOUSENUMBER + ', ' +
                i.POSTALCODE + ', ' +  i.COUNTRY + ', ' + i.CITY;
    }

    function fCreateList(data, manager)
    {
        data = data || [];

        var n = data.length
        ,   node;

        fClearList();

        while(n--)
        {
            node = $('<li>' + fCreateLiLabel(data[n]) +'</li>').
                click((function(item)
                {
                    return function()
                    {
                        console.log(item);
                        manager.get(item.ADDRESSID, function(data)
                        {
                            fFillFulForm(data[0]);
                        })
                    };
                })(data[n]));
            oList.append(node);
        };
        oList.slideDown();
    }

    function fClearList()
    {
        oList.slideUp();
        oList.html('');
    }

    function fError(txt)
    {
        alert(txt);
    }

    return {
        fillFulForm : fFillFulForm,
        clearForm : fClearForm,
        createList : fCreateList,
        clearList : fClearList,
        error : fError
    };
};
